import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { contactsApi } from '@/api/contacts'
import { useContactSocket } from '@/composables/useContactSocket'

/**
 * 联系人状态管理
 */
export const useContactsStore = defineStore('contacts', () => {
  // 使用联系人Socket功能
  const contactSocket = useContactSocket()

  // ==================== 状态数据 ====================
  
  // 好友列表
  const friends = ref<any[]>([])
  const friendGroups = ref<string[]>([])
  const totalFriends = ref(0)
  const onlineFriends = ref(0)

  // 好友申请
  const receivedRequests = ref<any[]>([])
  const sentRequests = ref<any[]>([])
  const pendingRequestsCount = ref(0)

  // 用户搜索
  const searchResults = ref<any[]>([])
  const searchLoading = ref(false)

  // 隐私设置
  const privacySettings = ref<any>({
    allowSearchByUsername: true,
    allowSearchByEmail: false,
    allowSearchByRealName: false,
    showOnlineStatus: true,
    allowFriendRequests: true,
    autoAcceptTeamMembers: false
  })

  // 加载状态
  const loading = ref(false)
  const error = ref<string | null>(null)

  // ==================== 计算属性 ====================

  const onlineFriendsCount = computed(() => {
    return friends.value.filter(friend => 
      contactSocket.isFriendOnline(friend.userId)
    ).length
  })

  const friendsByGroup = computed(() => {
    const grouped: Record<string, any[]> = {}
    friends.value.forEach(friend => {
      const group = friend.groupName || '默认分组'
      if (!grouped[group]) {
        grouped[group] = []
      }
      grouped[group].push(friend)
    })
    return grouped
  })

  // ==================== 好友管理 ====================

  /**
   * 获取好友列表
   */
  const getFriendsList = async (group?: string, keyword?: string) => {
    try {
      loading.value = true
      error.value = null

      const response = await contactsApi.getFriendsList(group, keyword)

      // {{ AURA-X: Modify - 修复联系人数据访问路径，从response.friends改为response.data.friends. Approval: 寸止(ID:fix-data-access). }}
      friends.value = response.data?.friends || []
      friendGroups.value = response.data?.groups || []
      totalFriends.value = response.data?.totalCount || 0
      onlineFriends.value = response.data?.onlineCount || 0

      console.log('✅ 好友列表加载成功:', response)
    } catch (err: any) {
      error.value = err.message || '获取好友列表失败'
      ElMessage.error(error.value)
      console.error('❌ 获取好友列表失败:', err)
    } finally {
      loading.value = false
    }
  }

  /**
   * 加载好友列表（别名方法）
   */
  const loadFriends = getFriendsList

  /**
   * 加载好友分组列表
   */
  const loadFriendGroups = async () => {
    try {
      // 重新获取好友列表，这会同时更新分组信息
      await getFriendsList()
    } catch (err: any) {
      console.error('❌ 加载好友分组失败:', err)
      ElMessage.error('加载分组信息失败')
    }
  }

  /**
   * 更新好友信息
   */
  const updateFriend = async (relationshipId: number, data: { groupName?: string, remark?: string }) => {
    try {
      const response = await contactsApi.updateFriend(relationshipId, data)
      
      // 更新本地数据
      const index = friends.value.findIndex(f => f.relationshipId === relationshipId)
      if (index > -1) {
        friends.value[index] = { ...friends.value[index], ...response }
      }

      ElMessage.success('好友信息更新成功')
      return response
    } catch (err: any) {
      ElMessage.error(err.message || '更新好友信息失败')
      throw err
    }
  }

  /**
   * 删除好友
   */
  const deleteFriend = async (relationshipId: number) => {
    try {
      await contactsApi.deleteFriend(relationshipId)
      
      // 从本地数据中移除
      const index = friends.value.findIndex(f => f.relationshipId === relationshipId)
      if (index > -1) {
        friends.value.splice(index, 1)
        totalFriends.value--
      }

      ElMessage.success('好友删除成功')
    } catch (err: any) {
      ElMessage.error(err.message || '删除好友失败')
      throw err
    }
  }

  // ==================== 好友申请管理 ====================

  /**
   * 发送好友申请
   */
  const sendFriendRequest = async (toUserId: number, message?: string) => {
    try {
      const response = await contactsApi.sendFriendRequest({ toUserId, message })
      
      // 添加到已发送申请列表
      sentRequests.value.unshift(response)

      ElMessage.success('好友申请已发送')
      return response
    } catch (err: any) {
      ElMessage.error(err.message || '发送好友申请失败')
      throw err
    }
  }

  /**
   * 处理好友申请
   */
  const handleFriendRequest = async (requestId: number, action: 'ACCEPT' | 'REJECT', responseMessage?: string) => {
    try {
      const response = await contactsApi.handleFriendRequest(requestId, { action, responseMessage })
      
      // 从待处理申请中移除
      const index = receivedRequests.value.findIndex(req => req.id === requestId)
      if (index > -1) {
        receivedRequests.value.splice(index, 1)
        pendingRequestsCount.value--
      }

      // 从Socket状态中移除
      contactSocket.removePendingRequest(requestId)

      if (action === 'ACCEPT') {
        ElMessage.success('好友申请已接受')
        // 重新加载好友列表
        await getFriendsList()
      } else {
        ElMessage.success('好友申请已拒绝')
      }

      return response
    } catch (err: any) {
      ElMessage.error(err.message || '处理好友申请失败')
      throw err
    }
  }

  /**
   * 获取收到的好友申请
   */
  const getReceivedRequests = async (status?: string, page = 0, size = 10) => {
    try {
      const response = await contactsApi.getReceivedRequests(status, page, size)
      
      // {{ AURA-X: Modify - 修复数据访问路径，从response.content改为response.data.content. Approval: 寸止(ID:fix-data-access). }}
      const content = response.data?.content || []
      if (page === 0) {
        receivedRequests.value = content
      } else {
        receivedRequests.value.push(...content)
      }

      // 更新待处理申请数量
      if (status === 'PENDING' || !status) {
        pendingRequestsCount.value = content.filter(req => req.status === 'PENDING').length
      }

      return response
    } catch (err: any) {
      ElMessage.error(err.message || '获取好友申请失败')
      throw err
    }
  }

  /**
   * 获取发送的好友申请
   */
  const getSentRequests = async (status?: string, page = 0, size = 10) => {
    try {
      const response = await contactsApi.getSentRequests(status, page, size)

      // {{ AURA-X: Modify - 修复数据访问路径，从response.content改为response.data.content. Approval: 寸止(ID:fix-data-access). }}
      const content = response.data?.content || []
      if (page === 0) {
        sentRequests.value = content
      } else {
        sentRequests.value.push(...content)
      }

      return response
    } catch (err: any) {
      ElMessage.error(err.message || '获取发送的申请失败')
      throw err
    }
  }

  // ==================== 用户搜索 ====================

  /**
   * 搜索用户
   */
  const searchUsers = async (keyword: string, searchType = 'ALL', excludeFriends = true, page = 0, size = 10) => {
    try {
      searchLoading.value = true
      
      const response = await contactsApi.searchUsers({
        keyword,
        searchType,
        excludeFriends,
        page,
        size
      })

      // {{ AURA-X: Modify - 修复数据访问路径，从response.content改为response.data.content. Approval: 寸止(ID:fix-data-access). }}
      const content = response.data?.content || []
      if (page === 0) {
        searchResults.value = content
      } else {
        searchResults.value.push(...content)
      }

      return response
    } catch (err: any) {
      ElMessage.error(err.message || '搜索用户失败')
      throw err
    } finally {
      searchLoading.value = false
    }
  }

  /**
   * 清空搜索结果
   */
  const clearSearchResults = () => {
    searchResults.value = []
  }

  // ==================== 隐私设置 ====================

  /**
   * 获取隐私设置
   */
  const getPrivacySettings = async () => {
    try {
      const response = await contactsApi.getPrivacySettings()
      // {{ AURA-X: Modify - 修复数据访问路径，从response改为response.data. Approval: 寸止(ID:fix-data-access). }}
      privacySettings.value = response.data || response
      return response.data || response
    } catch (err: any) {
      ElMessage.error(err.message || '获取隐私设置失败')
      throw err
    }
  }

  /**
   * 更新隐私设置
   */
  const updatePrivacySettings = async (settings: any) => {
    try {
      const response = await contactsApi.updatePrivacySettings(settings)
      privacySettings.value = response
      ElMessage.success('隐私设置更新成功')
      return response
    } catch (err: any) {
      ElMessage.error(err.message || '更新隐私设置失败')
      throw err
    }
  }

  // ==================== Socket.IO集成 ====================

  /**
   * 初始化Socket连接
   */
  const initSocket = async () => {
    await contactSocket.initContactSocket()
  }

  /**
   * 断开Socket连接
   */
  const disconnectSocket = () => {
    contactSocket.disconnectContactSocket()
  }

  /**
   * 检查好友是否在线
   */
  const isFriendOnline = (userId: number): boolean => {
    return contactSocket.isFriendOnline(userId)
  }

  // ==================== 初始化和清理 ====================

  /**
   * 初始化联系人数据
   */
  const initialize = async () => {
    try {
      await Promise.all([
        getFriendsList(),
        getReceivedRequests('PENDING'),
        getPrivacySettings(),
        initSocket()
      ])
    } catch (err) {
      console.error('❌ 联系人数据初始化失败:', err)
    }
  }

  /**
   * 清理数据
   */
  const cleanup = () => {
    friends.value = []
    friendGroups.value = []
    receivedRequests.value = []
    sentRequests.value = []
    searchResults.value = []
    totalFriends.value = 0
    onlineFriends.value = 0
    pendingRequestsCount.value = 0
    loading.value = false
    error.value = null
    
    disconnectSocket()
  }

  return {
    // 状态
    friends,
    friendGroups,
    totalFriends,
    onlineFriends,
    receivedRequests,
    sentRequests,
    pendingRequestsCount,
    searchResults,
    searchLoading,
    privacySettings,
    loading,
    error,

    // 计算属性
    onlineFriendsCount,
    friendsByGroup,

    // Socket状态
    contactSocket,

    // 方法
    getFriendsList,
    loadFriends,
    loadFriendGroups,
    updateFriend,
    deleteFriend,
    sendFriendRequest,
    handleFriendRequest,
    getReceivedRequests,
    getSentRequests,
    searchUsers,
    clearSearchResults,
    getPrivacySettings,
    updatePrivacySettings,
    isFriendOnline,
    initialize,
    cleanup
  }
})
